package com.zbkj.client.task;

import com.zbkj.client.utils.FileUtil;
import com.zbkj.common.model.client.digital.DpVoice;
import com.zbkj.client.vo.DpVoiceCjVo;
import com.zbkj.common.utils.OssUtil;
import com.zbkj.service.service.DpVoiceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

@Slf4j
@Component
public class DpVoiceUrlUpdateTask {
    @Resource
    private DpVoiceService dpVoiceService;
    @Resource
    private ThreadPoolTaskScheduler taskScheduler;

    public void start(DpVoice dpVoice, DpVoiceCjVo vo) {
        schedule(dpVoice, vo, 0);
    }

    private void schedule(DpVoice dpVoice, DpVoiceCjVo vo, int retryCount) {
        long delay = retryCount == 0 ? 0 : 2000; // 首次立即，后续2秒重试
        taskScheduler.schedule(() -> {
            try {
                doTask(dpVoice, vo, retryCount);
            } catch (Exception e) {
                log.error("DpVoiceUrlUpdateTask-定时任务异常", e);
            }
        }, new Date(System.currentTimeMillis() + delay));
    }

    private void doTask(DpVoice dpVoice, DpVoiceCjVo vo, int retryCount) {
        if (dpVoice == null || vo == null || vo.getFull() == null) return;
        // 重新查库获取最新对象
        DpVoice latestVoice = dpVoiceService.getById(dpVoice.getId());
        if (latestVoice == null || latestVoice.getIsDel() == 1) {
            log.warn("DpVoiceUrlUpdateTask-未找到定制语音记录，id={}", dpVoice.getId());
            return;
        }
        Integer userId = latestVoice.getUserId();
        Integer merId = latestVoice.getMerId();
//        String audioUrl = vo.getFull().getUrl();
        boolean success = true;
        try {
            // 只有audioUrl不为空且ossUrl为空才上传
            if (vo.getFull() != null && vo.getFull().getUrl() != null && !vo.getFull().getUrl().isEmpty()  && (latestVoice.getOssUrl() == null || latestVoice.getOssUrl().isEmpty())) {
                String audioUrl = vo.getFull().getUrl();

                String fileTypeLoop = FileUtil.getExtensionWithURI(audioUrl);

                String fileName = "audio_" + System.currentTimeMillis() + "." + fileTypeLoop;
                String ossAudioUrl = OssUtil.uploadFromUrlToOss(audioUrl, fileName, userId, merId, "audio", "dpvoice", "client");
                if (ossAudioUrl != null) {
                    latestVoice.setOssUrl(ossAudioUrl);
                } else {
                    success = false;
                }
            }
            latestVoice.setUpdateTime(new Date());
            dpVoiceService.updateById(latestVoice);
        } catch (Exception e) {
            log.error("DpVoiceUrlUpdateTask-异步上传OSS或更新数据库异常", e);
            success = false;
        }
        if (!success && retryCount < 3) {
            log.warn("DpVoiceUrlUpdateTask-上传OSS或更新数据库失败，准备重试，第{}次", retryCount + 1);
            schedule(latestVoice, vo, retryCount + 1);
        } else if (!success) {
            log.error("DpVoiceUrlUpdateTask-重试3次后仍失败");
        }
    }
} 